<?php

namespace App\Http\Middleware;

use App\Setting;
use Closure;

class ConfigSetting
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next, $prefix = '')
    {
        $settings = Setting::getSettings()->filter(function ($item) {
            return $item['value'];
        });
        $data = config()->get('settings') ?: [];
        $data = $data + $settings->pluck('value', 'slug')->toArray() + $settings->groupBy('group')->map(function ($item) {
                return $item->pluck('value', 'slug');
            })->toArray();
        config()->set('settings', $data);
        if ($name = config('settings.default.' . $prefix . '_name')) {
            config()->set('admin.name', $name);
        }
        if ($logo = config('settings.default.site_logo')) {
            config()->set('admin.logo', $logo);
        } elseif ($site_name = config('settings.default.site_name')) {
            config()->set('admin.logo', $site_name);
        }
        return $next($request);
    }
}
